<template>
  <view class="home">
    <!-- 顶部标题区域 -->
    <view class="header-section">
      <view class="header-bg"></view>
      <view class="header-content">
        <view class="header-title">
          <text class="title-main">安食溯</text>
          <text class="title-sub">守护舌尖上的安全</text>
        </view>
        <view class="header-decoration">
          <text class="decoration-icon">🌿</text>
        </view>
      </view>
    </view>

    <!-- 轮播图 -->
    <swiper class="swiper" v-if="banners.length > 0" :indicator-dots="true" :autoplay="true" :interval="3000" :duration="1000">
      <swiper-item v-for="(item, index) in banners" :key="index">
        <image class="swiper-item" :src="item.imageUrl || item.image" @click="bannerClick(item)"></image>
      </swiper-item>
    </swiper>

    <!-- 主要功能区域 -->
    <view class="main-function-area" v-if="isMerchant || isAdmin">
      <!-- 上方两个大按钮 -->
      <view class="big-buttons">
        <view class="big-button-wrapper">
          <view class="big-button-item" @click="goToFoodAppointment">
            <view class="big-button-icon">
              <text class="icon-text">🥬</text>
            </view>
            <text class="big-button-title">食用农产品预约</text>
          </view>
        </view>

        <view class="big-button-wrapper">
          <view class="big-button-item purple" @click="goToMarketAppointment">
            <view class="big-button-icon">
              <text class="icon-text">🏪</text>
            </view>
            <text class="big-button-title">农批市场预约</text>
          </view>
        </view>
      </view>

      <!-- 下方四个小按钮 -->
      <view class="small-buttons">
        <view class="small-button-item" @click="goToAppointmentRecords">
          <view class="small-button-icon">
            <text class="small-icon-text">📋</text>
          </view>
          <text class="small-button-text">预约记录</text>
        </view>
        <view class="small-button-item" @click="goToSupplierManage">
          <view class="small-button-icon">
            <text class="small-icon-text">🤝</text>
          </view>
          <text class="small-button-text">供货商管理</text>
        </view>
        <view class="small-button-item" @click="goToVehicleManage">
          <view class="small-button-icon">
            <text class="small-icon-text">🚚</text>
          </view>
          <text class="small-button-text">车辆管理</text>
        </view>
        <view class="small-button-item" @click="goToGoodsManage">
          <view class="small-button-icon">
            <text class="small-icon-text">📦</text>
          </view>
          <text class="small-button-text">商品管理</text>
        </view>
      </view>
    </view>

    <!-- 业务功能模块 -->
    <business-func v-if="!isMerchant" />

    <!-- 公告通知 -->
    <view class="notice-section">
      <view class="section-header">
        <view class="section-title">
          <view class="title-icon"></view>
          <text>公告通知</text>
        </view>
      </view>
      <view class="notice-list">
        <view class="notice-item" v-for="(notice, index) in notices" :key="index" @click="viewNotice(notice)">
          <text class="notice-title">{{ notice.title }}</text>
          <uni-icons type="right" size="14" color="#999"></uni-icons>
        </view>
      </view>
    </view>

    <!-- 食安咨询 -->
    <view class="consult-section">
      <view class="section-header">
        <view class="section-title">
          <view class="title-icon consult-icon"></view>
          <text>食安咨询</text>
        </view>
      </view>
      <view class="consult-list">
        <view class="consult-item" v-for="(consult, index) in consults" :key="index" @click="viewConsult(consult)">
          <text class="consult-title">{{ consult.title }}</text>
          <uni-icons type="right" size="14" color="#999"></uni-icons>
        </view>
      </view>
    </view>

    <!-- 自定义tabbar -->
    <custom-tabbar :current="0" />
  </view>
</template>

<script>
import { getActiveBannerList, clickBanner } from '@/api/business/banner.js';
import CustomTabbar from '@/components/custom-tabbar/custom-tabbar';
import BusinessFunc from '@/components/business-func/business-func';
import storage from '@/utils/storage';
import constant from '@/utils/constant';

export default {
  components: {
    CustomTabbar,
    BusinessFunc,
  },
  data() {
    return {
      banners: [],
      userRoles: [],
      isMerchant: false, // 是否是商户
      notices: [
        {
          id: 1,
          title: '关于开展2023年食用农产品安全专项检查的通知',
          content: '为进一步加强食用农产品质量安全监管...',
          publishTime: '2023-07-20',
        },
        {
          id: 2,
          title: '安阳市农产品追溯系统升级维护通知（2023年10月）',
          content: '系统将于2023年10月15日进行升级维护...',
          publishTime: '2023-07-15',
        },
      ],
      consults: [
        {
          id: 1,
          title: '如何查询农产品的追溯信息？详细步骤指南',
          content: '农产品追溯信息查询步骤...',
        },
        {
          id: 2,
          title: '农产品安全储存与运输的注意事项',
          content: '农产品在储存和运输过程中需要注意...',
        },
      ],
    };
  },
  computed: {
    // 检查是否有指定角色
    hasRole() {
      return (roleKey) => {
        return this.userRoles && this.userRoles.includes ? this.userRoles.includes(roleKey) : false;
      };
    },

    // 是否是管理员
    isAdmin() {
      return this.hasRole('admin');
    },
  },
  onLoad() {
    // 页面加载时获取数据
    this.loadUserRoles(); // 加载用户角色信息，用于权限控制
    this.loadBanners(); // 加载首页轮播图数据
    this.loadNotices(); // 加载公告数据（目前为TODO状态）
    this.loadConsults(); // 加载咨询数据（目前为TODO状态）
    uni.hideTabBar(); // 隐藏原生tabBar
  },
  onShow() {},
  methods: {
    // 加载用户角色
    loadUserRoles() {
      try {
        // 从存储中获取用户角色信息
        const roles = storage.get(constant.roles) || [];
        console.log('从storage获取的角色信息:', roles);
        if (roles && roles.length > 0) {
          // roles可能是对象数组，需要提取roleKey
          this.userRoles = roles.map((role) => {
            if (typeof role === 'object' && role.roleKey) {
              return role.roleKey;
            }
            return role;
          });
          console.log('处理后的用户角色:', this.userRoles);

          // 判断是否是商户角色
          this.isMerchant = this.userRoles.includes('merchant');

          console.log('是否为商户:', this.isMerchant);
        }
      } catch (error) {
        console.error('加载用户角色失败:', error);
      }
    },

    // 加载轮播图
    async loadBanners() {
      try {
        const response = await getActiveBannerList();
        if (response.code === 200) {
          this.banners = response.data || [];
        }
      } catch (error) {
        console.error('加载轮播图失败:', error);
        // 失败时不显示轮播图
        this.banners = [];
      }
    },

    // 轮播图点击
    async bannerClick(item) {
      // 统计点击数
      if (item.bannerId) {
        try {
          await clickBanner(item.bannerId);
        } catch (error) {
          console.error('点击统计失败:', error);
        }
      }

      // 跳转链接
      if (item.linkUrl || item.url) {
        uni.navigateTo({
          url: item.linkUrl || item.url,
        });
      } else {
        console.log('轮播图点击:', item.title);
      }
    },

    // 查看公告
    viewNotice(notice) {
      uni.navigateTo({
        url: `/pages/common/textview/index?title=${notice.title}&content=${notice.content}`,
      });
    },

    // 查看咨询
    viewConsult(consult) {
      uni.navigateTo({
        url: `/pages/common/textview/index?title=${consult.title}&content=${consult.content}`,
      });
    },

    // 加载公告数据
    loadNotices() {
      // TODO: 调用API获取公告数据
    },

    // 加载咨询数据
    loadConsults() {
      // TODO: 调用API获取咨询数据
    },

    // 主要功能跳转
    goToFoodAppointment() {
      // 检查用户角色
      if (this.isMerchant || this.isAdmin) {
        // 商户可以发起预约
        uni.navigateTo({
          url: '/pages/appointment/food',
        });
      } else {
        // 非商户跳转到预约记录查看页面
        uni.showToast({
          title: '仅商户可发起预约',
          icon: 'none',
          duration: 2000,
        });
      }
    },

    goToMarketAppointment() {
      // 检查用户角色
      if (this.isMerchant || this.isAdmin) {
        // 商户可以发起预约
        uni.navigateTo({
          url: '/pages/appointment/market',
        });
      } else {
        // 非商户跳转到预约记录查看页面
        uni.showToast({
          title: '仅商户可发起预约',
          icon: 'none',
          duration: 2000,
        });
      }
    },

    // 跳转到预约记录
    goToAppointmentRecords() {
      uni.navigateTo({
        url: '/pages/appointment/record',
      });
    },

    // 跳转到供货商管理
    goToSupplierManage() {
      uni.navigateTo({
        url: '/pages/supplier/list',
      });
    },

    // 跳转到车辆管理
    goToVehicleManage() {
      uni.navigateTo({
        url: '/pages/vehicle/list',
      });
    },

    // 跳转到商品管理
    goToGoodsManage() {
      uni.navigateTo({
        url: '/pages/goods/list',
      });
    },
  },
};
</script>

<style scoped>
.home {
  background: linear-gradient(180deg, #e8f5e9 0%, #f1f8e9 100%);
  min-height: 100vh;
  padding-bottom: 120rpx; /* 为自定义tabbar留出空间 */
  position: relative;
}

/* 顶部标题区域 */
.header-section {
  position: relative;
  height: 200rpx;
  margin-bottom: 20rpx;
  overflow: hidden;
}

.header-bg {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: linear-gradient(135deg, rgba(76, 175, 80, 0.1) 0%, rgba(139, 195, 74, 0.1) 100%);
  border-bottom-left-radius: 50% 30rpx;
  border-bottom-right-radius: 50% 30rpx;
}

.header-content {
  position: relative;
  padding: 40rpx 40rpx 30rpx;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-title {
  display: flex;
  flex-direction: column;
}

.title-main {
  font-size: 42rpx;
  font-weight: bold;
  color: #2e7d32;
  margin-bottom: 10rpx;
}

.title-sub {
  font-size: 26rpx;
  color: #66bb6a;
}

.header-decoration {
  position: absolute;
  right: 40rpx;
  top: 50%;
  transform: translateY(-50%);
}

.decoration-icon {
  font-size: 80rpx;
  opacity: 0.3;
}

/* 轮播图 */
.swiper {
  height: 300rpx;
  border-radius: 20rpx;
  margin: 20rpx;
  overflow: hidden;
}

.swiper-item {
  width: 100%;
  height: 100%;
  border-radius: 20rpx;
}

/* 主要功能区域 */
.main-function-area {
  padding: 20rpx;
  background: rgba(255, 255, 255, 0.98);
  margin: 20rpx;
  border-radius: 20rpx;
  box-shadow: 0 8rpx 32rpx rgba(76, 175, 80, 0.08);
  backdrop-filter: blur(10px);
  border: 1rpx solid rgba(76, 175, 80, 0.1);
}

/* 上方两个大按钮 */
.big-buttons {
  display: flex;
  justify-content: space-between;
  margin-bottom: 30rpx;
}

.big-button-wrapper {
  width: 48%;
}

.big-button-item {
  width: 100%;
  background: linear-gradient(135deg, #e8f4fd 0%, #d6e9fa 100%);
  border-radius: 16rpx;
  padding: 30rpx 20rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  min-height: 160rpx;
  border: 2rpx solid #e0e8f0;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  position: relative;
  overflow: hidden;
}

.big-button-item::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: linear-gradient(135deg, rgba(255, 255, 255, 0) 0%, rgba(255, 255, 255, 0.2) 50%, rgba(255, 255, 255, 0) 100%);
  transform: translateX(-100%);
  transition: transform 0.6s ease;
}

.big-button-item:hover::before {
  transform: translateX(100%);
}

.big-button-item.purple {
  background: linear-gradient(135deg, #f4e8fd 0%, #e9d6fa 100%);
  border-color: #f0e0f8;
}

.big-button-item:active {
  transform: scale(0.98);
  opacity: 0.9;
}

.big-button-icon {
  width: 72rpx;
  height: 72rpx;
  background-color: rgba(255, 255, 255, 0.8);
  border-radius: 16rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 16rpx;
}

.icon-text {
  font-size: 60rpx;
}

.small-icon-text {
  font-size: 44rpx;
}

.big-button-title {
  font-size: 30rpx;
  color: #333;
  font-weight: 500;
  margin-bottom: 8rpx;
}

.big-button-desc {
  font-size: 24rpx;
  color: #666;
}

/* 下方四个小按钮 */
.small-buttons {
  display: flex;
  justify-content: space-between;
}

.small-button-item {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 20rpx 10rpx;
  transition: all 0.2s ease;
}

.small-button-item:active {
  opacity: 0.7;
  transform: scale(0.95);
}

.small-button-icon {
  width: 56rpx;
  height: 56rpx;
  background-color: #f8f8f8;
  border-radius: 12rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 12rpx;
}

.small-button-text {
  font-size: 24rpx;
  color: #333;
}

/* 通用区块样式 */
.notice-section,
.consult-section {
  background: rgba(255, 255, 255, 0.95);
  margin: 20rpx;
  border-radius: 20rpx;
  padding: 30rpx;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.05);
  backdrop-filter: blur(10px);
}

.section-header {
  margin-bottom: 30rpx;
}

.section-title {
  display: flex;
  align-items: center;
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.title-icon {
  width: 8rpx;
  height: 32rpx;
  background-color: #1890ff;
  border-radius: 4rpx;
  margin-right: 20rpx;
}

.consult-icon {
  background-color: #52c41a;
}

.dynamic-icon {
  background-color: #722ed1;
}

/* 列表项 */
.notice-list,
.consult-list {
  display: flex;
  flex-direction: column;
}

.notice-item,
.consult-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 25rpx 0;
  border-bottom: 1rpx solid #f0f0f0;
}

.notice-item:last-child,
.consult-item:last-child {
  border-bottom: none;
}

.notice-title,
.consult-title {
  font-size: 28rpx;
  color: #333;
  flex: 1;
  line-height: 1.5;
}
</style>
